iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 23
0
Software Development

刷刷題 or Alan Becker's game 製作 is a question 系列 第 23

(Hard) 25. Reverse Nodes in k-Group

  • 分享至 

  • xImage
  •  

25. Reverse Nodes in k-Group

tags: 刷題

Level: Hard

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

Follow up:

Could you solve the problem in O(1) extra memory space?
You may not alter the values in the list's nodes, only nodes itself may be changed.


題意:
每k個為一組,reverse。
不足則為原樣。

解法:
取出link list的值: 以每k個取出
放進 暫時的list 進行 reverse
Note: 不足的不用 reverse
每做一次 就放入最終的list

最後 list 轉 link list

程式碼

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        dummyNode = ListNode()
        dummyNode = head 
        ansList = [] 
        while head!=None:
            cnt = k
            tmpList = []
            for i in range(cnt):
                if head == None:
                    break
                #print(head.val)
                tmpList.append(head.val)
                head = head.next
            if len(tmpList)==cnt:    
                tmpList.reverse()    
            #print(tmpList)
            #ansList.append(tmpList)
        #print(ansList)
            for j in tmpList:
                #print(j)
                ansList.append(j)
        print(ansList)
        
        ansNode = dummyNode
        for k in ansList:
            dummyNode.val = k
            dummyNode = dummyNode.next 
        print(ansNode)
        return ansNode        

Result
時間 不太行
空間 也需額外的list空間


上一篇
(Medium) 24. Swap Nodes in Pairs
下一篇
目前做過最有趣的一題 : 26. Remove Duplicates from Sorted Array
系列文
刷刷題 or Alan Becker's game 製作 is a question 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言